import importlib
import sys
from pathlib import Path

from ai_core.utils.util import Util


class AIFactory:
    def __init__(self,config):
        self.config = Util.get_config()


    def create_asr_instance(self):
        model = self.config['select_module']["ASR"]
        config_ = self.config["ASR"][model]

        module_file = config_["type"]
        file_path = Path('ai_core') / 'asr' / f'{module_file}.py'

        if file_path.exists():
            lib_name = '.'.join(file_path.with_suffix('').parts)
            if lib_name not in sys.modules:
                sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
            return sys.modules[lib_name].ASRModule(config_)

    def create_instance(self,type: str, base_class):
        model = self.config['select_module'][type]
        config_ = self.config[type][model]

        module_file = config_["type"]
        file_path = Path('ai_core') / type.lower() / f'{module_file}.py'

        if file_path.exists():
            lib_name = '.'.join(file_path.with_suffix('').parts)
            if lib_name not in sys.modules:
                sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
            class_name = f'{type}Module'
            return getattr(sys.modules[lib_name], class_name)(config_)
        raise ValueError(f"不支持的类型，{module_file}")